using System;
using System.Collections.Generic;
using System.Text;
using System.Timers;
using SpoonCore.Message;

namespace SpoonCore.Handler.Core
{
	internal class ExchangeManager
	{
		private SpoonClient _client;
		private Timer _timer = new Timer(1000);
		private SortedList<byte, SortedList<ClientInfo, SearchMask>> _registerList = new SortedList<byte, SortedList<ClientInfo, SearchMask>>();

		public ExchangeManager(SpoonClient client)
		{
			_client = client;

			_timer.Elapsed += new ElapsedEventHandler(TimerElapsed);
			_timer.Start();
		}

		private void TimerElapsed(object sender, ElapsedEventArgs e)
		{
			_client.RoutingTable.Refresh();
			//_client.LeaveTable.Refresh();
		}

		internal void Receive(ExchangeMessage msg, ClientInfo destClient)
		{
			if (msg.Type == ExchangeMessage.ExchangeType.Request)
			{
				ExchangeMessage res = new ExchangeMessage();
				res.Type = ExchangeMessage.ExchangeType.Response;
				res.SearchList = msg.SearchList;
				res.Clients.AddRange(_client.RoutingTable.FindByMask(msg.SearchList));
				if (msg.LeaveSet) res.Clients.AddRange(_client.LeaveTable.Clients);

				if (res.Clients.Count > 0)
				{
					Console.WriteLine("Send new info: " + res.Clients.Count);
					destClient.Send(res);
				}

				// register for next updates
				foreach (SearchMask mask in msg.SearchList)
				{
					if (!_registerList.ContainsKey(mask.Level)) _registerList.Add(mask.Level, new SortedList<ClientInfo, SearchMask>());
					if (!_registerList[mask.Level].ContainsKey(destClient)) _registerList[mask.Level].Add(destClient, mask);
					else _registerList[mask.Level][destClient] = mask;
				}
				
			}

			if (msg.Type == ExchangeMessage.ExchangeType.Response)
			{
				_client.AddClient(msg.Clients);
			}
		}
	}
}